package com.dctp.ems.controller;

import com.dctp.common.controller.BaseController;
import com.dctp.common.db.DictionaryDb;
import com.dctp.common.utils.DateUtil;
import com.dctp.common.vo.JsonResult;
import com.dctp.common.vo.PageResult;
import com.dctp.ems.config.OpsLog;
import com.dctp.ems.interceptor.OpsLogInterceptor;
import com.jfinal.aop.Before;
import com.jfinal.core.Path;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import java.util.List;

@Path("/dictionary")
public class DictionaryController extends BaseController {

    /**
     * GET /dictionary/typeList
     * 获取所有字典类型（去重，按display_order排序）
     */
    public void typeList() {
        List<Record> list = Db.find("SELECT DISTINCT dict_type FROM dctp_dictionary order by dict_type ASC");
        renderJson(JsonResult.successWithData(list));
    }

    /**
     * GET /dictionary/list
     * 分页获取某类型下的字典项
     * 参数：dict_type, page, pageSize
     */
    public void list() {
        String dictType = getPara("dict_type");
        int page = getInt("currentPage", 1);
        int pageSize = getInt("pageSize", 10);
        String select = "SELECT id, dict_code, dict_value, status, description, display_order, create_time, update_time ";
        String from = "FROM dctp_dictionary WHERE dict_type = ? ORDER BY display_order ASC, id ASC";
        var p = Db.paginate(page, pageSize, select, from, dictType);
        renderJson(JsonResult.successWithData(
            new PageResult<>(p.getList(), p.getTotalRow(), pageSize, page)
        ));
    }

    /**
     * POST /dictionary/save
     * 新增或更新字典项（有id为更新，无id为新增）
     */
    @Before({Tx.class, OpsLogInterceptor.class})
    @OpsLog(module = "系统参数",
            action = "参数修改",
            table = "dctp_dictionary",
            addLabel = "description",
            addKey = "dict_value")
    public void save() {
        Record body = jsonBody();
        Long id = body.getLong("id");
        String dictType = body.getStr("dict_type");
        String dictCode = body.getStr("dict_code");
        // 新增时校验 dict_code 不能重复
        if (id == null) {
            boolean exists = Db.queryInt(
                "SELECT COUNT(1) FROM dctp_dictionary WHERE dict_type = ? AND dict_code = ?", dictType, dictCode
            ) > 0;
            if (exists) {
                renderJson(JsonResult.failWithMessage("字典键已存在，请勿重复添加"));
                return;
            }
            // 新增
            body.remove("id");
            body.set("create_time", DateUtil.now());
            body.set("update_time", DateUtil.now());
            boolean ok = Db.save("dctp_dictionary", body);

            renderJson(ok ? JsonResult.success() : JsonResult.failWithMessage("保存失败"));
        } else {
            // 更新时也要校验不能改成重复的 code
            boolean exists = Db.queryInt(
                "SELECT COUNT(1) FROM dctp_dictionary WHERE dict_type = ? AND dict_code = ? AND id <> ?", dictType, dictCode, id
            ) > 0;
            if (exists) {
                renderJson(JsonResult.failWithMessage("字典键已存在，请勿重复"));
                return;
            }
            body.set("update_time", DateUtil.now());
            boolean ok = Db.update("dctp_dictionary", body);


            renderJson(ok ? JsonResult.success() : JsonResult.failWithMessage("更新失败"));
        }
    }

    /**
     * POST /dictionary/delete/:id
     * 删除单个字典项
     */
    @Before({Tx.class, OpsLogInterceptor.class})
    @OpsLog(module = "系统参数",
            action = "删除参数",
            table = "dctp_dictionary",
            addLabel = "description",
            addKey = "dict_value")
    public void delete() {
        Long id = getParaToLong(0);
        if (id == null) {
            renderJson(JsonResult.failWithMessage("参数缺失"));
            return;
        }
        Record dic = Db.findById("dctp_dictionary", id);
        if (dic == null) {
            renderJson(JsonResult.failWithMessage("状态异常"));
            return;
        }
        setAttr("jsonBody",dic);
        int r = Db.deleteById("dctp_dictionary", id) ? 1 : 0;
        renderJson(r == 1 ? JsonResult.success() : JsonResult.failWithMessage("删除失败或记录不存在"));
    }

    /**
     * POST /dictionary/deleteType
     * 批量删除某类型下所有字典项，dict_type 通过 query/body 传参
     */
    @Before(Tx.class)
    public void deleteDictType() {
        String dictType = getPara("dict_type");
        if (dictType == null || dictType.isEmpty()) {
            renderJson(JsonResult.failWithMessage("参数缺失"));
            return;
        }
        int count = Db.delete("DELETE FROM dctp_dictionary WHERE dict_type = ?", dictType);
        renderJson(count > 0 ? JsonResult.success() : JsonResult.failWithMessage("删除失败或无记录"));
    }

    public void getValue() {

        String dictCode = getPara("dict_code");
        if (dictCode == null || dictCode.isEmpty()) {
            renderJson(JsonResult.success());
            return;
        }
        String dictValue = DictionaryDb.getValueByCode(dictCode);
        renderJson(JsonResult.successWithData(dictValue));
    }
}
